package vlms.cronjob;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;

import java.util.Set;
import java.util.TimerTask;

import vlms.bean.Person;
import vlms.dao.PersonDAO;
import vlms.util.DateConvert;


public class Fine extends TimerTask {
	
	float finePerDayPerMovie = 5;
	
	public Fine(float finePerDayPerMovie) {
		this.finePerDayPerMovie = finePerDayPerMovie; 		
	}
	
	public void run() {
	
		Connection con = null;
		try {
			con = DriverManager.getConnection("jdbc:user_mysql:");
			PersonDAO personDAO = new PersonDAO();
			HashMap<Integer,Integer> personList = new HashMap<Integer,Integer>();
			Calendar cal = Calendar.getInstance();
			
			PreparedStatement ps = null;
			
			ps = con.prepareStatement("Select personId,count(issueId) as movieCount FROM issuedmovie WHERE returnDate IS NULL and dueDate < ? GROUP BY personId");
			
			ps.setDate(1, DateConvert.convertUtilToSQLdate(cal.getTime()));
			
			ResultSet result=ps.executeQuery();
			 
			while(result.next()) {
				personList.put(result.getInt("personId"), result.getInt("movieCount"));
			}
			
			if(personList.size() > 0) {
				
				Set<Integer> keys = personList.keySet();
				
				Iterator<Integer> it = keys.iterator();
				while(it.hasNext()) {
					int personId = (Integer) it.next();
					Person oPerson = new Person(personDAO.findByPrimaryKey(personId, con));
					
					float fine = oPerson.getFine() + finePerDayPerMovie * personList.get(personId);
					oPerson.setFine(fine);
					//ps = con.prepareStatement("UPDATE person SET fine = fine + " + fine + " WHERE personId = " + personId + "");
					int rowCount = personDAO.update(personId, oPerson, con);			
				
					 
					if(rowCount > 0) {
						con.commit();
					}
				}	
			}
			
		}catch(SQLException e) {
			
			e.printStackTrace();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		finally{
			try {
				
				con.close();
			} catch (SQLException e) {				
				e.printStackTrace();
			}
		}
	
	}
}
